// 获取openid Promise
const getOpenid = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success: (res) => {
                if (res.code) {
                    const baseUrl = getBaseUrl();
                    wx.request({
                        url: `${baseUrl}/home/index/login`,
                        method: 'POST',
                        data: {
                            code: res.code,
                        },
                        success: (res) => {
                            const response = res.data;
                            if (response.data && response.data.openid) {
                                resolve(response.data);
                            } else {
                                reject(new Error('获取openid失败'));
                            }
                        },
                        fail: (err) => {
                            console.error('请求登录接口失败', err);
                            reject(err);
                        }
                    });
                } else {
                    reject(new Error('wx.login失败'));
                }
            },
            fail: (err) => {
                console.error('wx.login调用失败', err);
                reject(err);
            }
        });
    });
};

// 公共登录函数
const doLogin = () => {
    return getOpenid()
        .then(data => {
            // 存储用户信息到本地
            wx.setStorageSync('openid', data.openid);
            return data;
        })
        .catch(err => {
            console.error('登录失败', err);
            throw err;
        });
};

// 检查是否已登录
const checkLogin = () => {
    const openid = wx.getStorageSync('openid');
    return !!openid;
};

// 退出登录
const logout = () => {
    wx.removeStorageSync('openid');
};

// 引入环境配置
const { getBaseUrl } = require('../config/env');

module.exports = {
    getOpenid,
    doLogin,
    checkLogin,
    logout
};